import { defHttp } from '/@/utils/http/axios';
import { LoginParams, LoginResultModel, GetUserInfoModel } from './model/userModel';

import { ErrorMessageMode } from '/#/axios';
import { useMessage } from '/@/hooks/web/useMessage';
import { useUserStoreWithOut } from '/@/store/modules/user';
import { setAuthCache } from '/@/utils/auth';
import { TOKEN_KEY } from '/@/enums/cacheEnum';
import { router } from '/@/router';
import { PageEnum } from '/@/enums/pageEnum';
import { useGlobSetting } from '/@/hooks/setting';
import { stringFormat } from '/@/utils/common/compUtils';

const { createErrorModal } = useMessage();
const globSetting = useGlobSetting();
enum Api {
  Login = '/api-uaa/oauth/token',
  LogoutCheckToken = '/api-uaa/oauth/check_token?token={0}',
  LogoutRemoveToken = '/api-uaa/oauth/remove/token?redirect_uri={0}&access_token={1}',
  Logout = '/api-uaa/oauth/remove/token',
  GetUserInfo = '/api-upms/sys/user/current',
  // 获取系统权限
  // 1、系统
  // 1、查询用户拥有的按钮/表单访问权限
  // 2、所有权限
  // 3、系统安全模式
  GetPermCode = '/api-upms/sys/permission/current',
  //新加的获取图形验证码的接口
  getInputCode = '/api-uaa/validata/code',
  //获取短信验证码的接口
  getCaptcha = '/api-uaa/validata/smsCode/{0}',
  //注册接口
  registerApi = '/api-upms/sys/user/register',
  //校验用户接口
  checkOnlyUser = '/sys/user/checkOnlyUser',
  //SSO登录校验
  validateCasLogin = '/api-uaa/oauth/token',
  //校验手机号
  mobileVerify = '/api-uaa/offline/mobileVerification',
  //修改密码
  passwordChange = '/api-uaa/offline/passwordChange',
  //第三方登录
  thirdLogin = '/api-upms/thirdLogin/getLoginUser',
  //获取二维码信息
  getLoginQrcode = '/api-uaa/validata/qr/getLoginQrcode',
  //监控二维码扫描状态
  getQrcodeToken = '/api-uaa/validata/qr/getQrcodeToken/{0}',
}

/**
 * @description: user login api
 */
export function loginApi(params: LoginParams, mode: ErrorMessageMode = 'modal') {
  return defHttp.post<LoginResultModel>(
    {
      url: Api.Login,
      params,
      headers: {
        Authorization: 'Basic ' + btoa(globSetting.clientId + ':' + globSetting.clientSecret),
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
      },
    },
    {
      errorMessageMode: mode,
    }
  );
}

/**
 * SSO登录校验
 */
export async function validateCasLogin(params) {
  return defHttp.post(
    {
      url: Api.validateCasLogin,
      params,
      headers: {
        Authorization: 'Basic ' + btoa(globSetting.clientId + ':' + globSetting.clientSecret),
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
      },
    },
    { isTransformResponse: true }
  );
}

/**
 * @description: getUserInfo
 */
export function getUserInfo() {
  return defHttp.get<GetUserInfoModel>({ url: Api.GetUserInfo }, {}).catch((e) => {
    // update-begin--author:zyf---date:20220425---for:【VUEN-76】捕获接口超时异常,跳转到登录界面
    if (e && (e.message.includes('timeout') || e.message.includes('401'))) {
      //接口不通时跳转到登录界面
      const userStore = useUserStoreWithOut();
      userStore.setToken('');
      setAuthCache(TOKEN_KEY, null);
      // update-begin-author:sunjianlei date:20230306 for: 修复登录成功后，没有正确重定向的问题
      router.push({
        path: PageEnum.BASE_LOGIN,
        query: {
          // 传入当前的路由，登录成功后跳转到当前路由
          redirect: router.currentRoute.value.fullPath,
        },
      });
      // update-end-author:sunjianlei date:20230306 for: 修复登录成功后，没有正确重定向的问题
    }
    // update-end--author:zyf---date:20220425---for:【VUEN-76】捕获接口超时异常,跳转到登录界面
  });
}

export function getPermCode() {
  return defHttp.get({ url: Api.GetPermCode });
}

export function doLogout() {
  return defHttp.get({ url: Api.Logout });
}

export function doLogoutCheckToken(accessToken) {
  const checktokenurl = stringFormat(Api.LogoutCheckToken, accessToken);
  return defHttp.get({ url: checktokenurl }, { isTransformResponse: false });
}

export function doLogoutRemoveToken(accessToken) {
  const sevice_login = window.location.protocol + '//' + window.location.host + '/login';
  const serviceUrl = encodeURIComponent(sevice_login);
  const sevice_access_token = stringFormat(Api.LogoutRemoveToken, serviceUrl, accessToken);
  if (accessToken) {
    window.location = sevice_access_token;
  } else {
    window.location = sevice_login;
  }
}

export function getCodeInfo(currdatetime) {
  const url = Api.getInputCode + `/${currdatetime}`;
  return defHttp.get({ url: url });
}

/**
 * @description: 获取短信验证码
 */
export function getCaptcha(params) {
  const url = stringFormat(Api.getCaptcha, params.mobile);
  return new Promise((resolve, reject) => {
    defHttp.get({ url: url, params }, { isTransformResponse: false }).then((res) => {
      if (res.success) {
        resolve(true);
      } else {
        createErrorModal({ title: '错误提示', content: res.msg || '未知问题' });
        reject();
      }
    }).catch((res)=>{
      createErrorModal({ title: '错误提示', content: res.message || '未知问题' });
      reject();
    });
  });
}

/**
 * @description: 注册接口
 */
export function register(params) {
  return defHttp.post({ url: Api.registerApi, params }, { isReturnNativeResponse: true });
}

/**
 *校验用户是否存在
 * @param params
 */
export const checkOnlyUser = (params) => defHttp.get({ url: Api.checkOnlyUser, params }, { isTransformResponse: false });
/**
 *校验手机号码
 * @param params
 */
export const mobileVerify = (params) => defHttp.post({ url: Api.mobileVerify, params }, { isTransformResponse: false });
/**
 *密码修改
 * @param params
 */
export const passwordChange = (params) => defHttp.get({ url: Api.passwordChange, params }, { isTransformResponse: false });
/**
 * @description: 第三方登录
 */
export function thirdLogin(params, mode: ErrorMessageMode = 'modal') {
  //==========begin 第三方登录/auth2登录需要传递租户id===========
  let tenantId = '0';
  if (!params.tenantId) {
    tenantId = params.tenantId;
  }
  //==========end 第三方登录/auth2登录需要传递租户id===========
  return defHttp.get<LoginResultModel>(
    {
      url: `${Api.thirdLogin}/${params.token}/${params.thirdType}/${tenantId}`,
    },
    {
      errorMessageMode: mode,
    }
  );
}

/**
 * 获取登录二维码信息
 */
export function getLoginQrcode() {
  const url = Api.getLoginQrcode;
  return defHttp.get({ url: url });
}

/**
 * 监控扫码状态
 */
export function getQrcodeToken(params) {
  const url = stringFormat(Api.getQrcodeToken, params.qrcodeId);
  return defHttp.get({ url: url, params });
}
